#include "Socket.hpp"
#include "Protocol.hpp"
#include "Common.hpp"
#include <memory>

using namespace SocketModule;

void GetFromStdin(int *x, int *y, char *oper)
{
    std::cout << "Please Enter x: ";
    std::cin >> *x;
    std::cout << "Please Enter y: ";
    std::cin >> *y;
    std::cout << "Please Enter oper: ";
    std::cin >> *oper;
}

// ./tcpclient server_ip server_port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " server_ip server_port" << std::endl;
        exit(USAGE_ERR);
    }
    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);
    InetAddr addr(port, ip);

    // 1.创建TCP套接字
    std::unique_ptr<Socket> sock = std::make_unique<TCPSocket>(addr, Type::CLIENT);

    // 2.连接客户端
    sock->ConnectOrDie(addr);

    std::unique_ptr<Protocol> protocol = std::make_unique<Protocol>();
    std::string data;
    while (true)
    {
        // 3.客户端从键盘获取数据，序列化
        // x=10,y=20,oper='+' -> {"x":10 "y":20 "oper":'+'}
        int x, y;
        char oper;
        GetFromStdin(&x, &y, &oper);
        Request req;
        req.SetRequest(x, y, oper);
        std::string json_package = req.Serialize();

        // std::cout << "----------请求序列化-----------" << std::endl;
        // std::cout << json_package << std::endl;
        // std::cout << "----------请求序列化-----------" << std::endl;

        // 4.添加协议报头
        // {"x":10 "y":20 "oper":'+'} -> 50\r\n{"x":10 "y":20 "oper":'+'}\r\n
        protocol->Encode(json_package);

        // std::cout << "------------添加协议报头-----------" << std::endl;
        // std::cout << json_package << std::endl;
        // std::cout << "------------添加协议报头-----------" << std::endl;

        // 5.发送给服务端
        ssize_t n = sock->Send(json_package);
        if (n <= 0)
        {
            LOG(LogLevel::WARNING) << "send error";
            continue;
        }

        // 6.获取响应
        protocol->GetResponse(sock, data);
    }

    sock->Close();
    return 0;
}